package com.wishwall.web.filters;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import com.sun.servicetag.UnauthorizedAccessException;
import com.wishwall.auth.SecurityContext;
import com.wishwall.persistence.PersistenceContext;
import com.wishwall.web.utils.RequestHelper;

/**
 * 
 * @author yavor.gologanov
 *
 */
public class RestSecurityFilter extends AbstractFilter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
			throws IOException, ServletException {
		
		try {
			PersistenceContext persistenceContext = RequestHelper.getPersistenceContext(request);
			String[] credentials = RequestHelper.getUserCredentials(request);
			
			SecurityContext securityContext = SecurityContext.createSecurityContext(persistenceContext, credentials);
			RequestHelper.setSecurityContext(request, securityContext);
			
			doNextFilter(request, response, chain);
		}
		catch (UnauthorizedAccessException e) {
			response.setContentType(MediaType.APPLICATION_JSON);
			((HttpServletResponse) response).getWriter().write(e.getMessage());
			((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		}		
	}
	
}
